package com.tuyan.aixiang.activity.home;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.tuyan.aixiang.MainApplication;
import com.tuyan.aixiang.R;
import com.tuyan.aixiang.activity.home.control.ControlFragment;
import com.tuyan.aixiang.activity.home.map.MapFragment;
import com.tuyan.aixiang.activity.home.me.MeFragment;
import com.tuyan.aixiang.activity.home.msg.MsgFragment;
import com.tuyan.aixiang.api.HttpClient;
import com.tuyan.aixiang.api.helper.ResultTransformer;
import com.tuyan.aixiang.api.helper.RxSchedulers;
import com.tuyan.aixiang.common.AppData;
import com.tuyan.aixiang.common.BaseActivity;
import com.tuyan.aixiang.common.BasePresenter;
import com.tuyan.aixiang.common.lang.VoidFunction;
import com.tuyan.aixiang.component.BYTab;
import com.tuyan.aixiang.enums.LaunchMode;
import com.tuyan.aixiang.model.UserInfo;
import com.tuyan.aixiang.receiver.MessageHandler;
import com.tuyan.aixiang.util.ToastUtil;
import com.videogo.openapi.EZOpenSDK;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;
import butterknife.BindView;
import io.reactivex.disposables.Disposable;
//import pub.devrel.easypermissions.AfterPermissionGranted;
//import pub.devrel.easypermissions.EasyPermissions;

/**
 * 应用首页
 */
public class HomeActivity extends BaseActivity<BasePresenter> implements Home {

    @BindView(R.id.vp_container)
    ViewPager vpContainer;

    @BindView(R.id.byt_tab)
    BYTab bytTab;

    private List<Fragment> fragments = new ArrayList<>();

    public static void start(Context context) {
        Intent intent = new Intent(context, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //        String accessToken = "at.811ynscu1tdagbqi1gbstyrh9emqfeuo-173t8kn4iw-1mbkxfz-ocfowmucz";
//        Disposable disposable = HttpClient.getYsApi().getToken(M.m().put("appKey", Constant.YS_APP_KEY).put("appSecret", Constant.YS_APP_SEC))
//                .compose(RxSchedulers.io_main()).compose(ResultTransformer.handleResult())
//                .subscribe(data -> {
//                    String atoken = data.get().getAccessToken();
//                    EZOpenSDK.getInstance().setAccessToken(atoken);
//
//                }, throwable -> {
//
//                });
//        addDisposable(disposable);
    }

    @Override
    public void bindView() {
        super.bindView();

        // 绑定推送账号
        MainApplication.bindAccount(AppData.getUserInfo().getMobile());

        immersion();

        bytTab.init(AppData.getLanuchMode());

        ControlFragment controlFragment = new ControlFragment();
        controlFragment.setContainer(this);

        MeFragment meFragment = new MeFragment();
        MsgFragment msgFragment = new MsgFragment();

        fragments.add(controlFragment);
        fragments.add(msgFragment);

        // 企业版添加地图
        if (AppData.getLanuchMode().equals(LaunchMode.ENTERPRISE.getValue())) {
            MapFragment mapFragment = new MapFragment();
            fragments.add(mapFragment);
        }

        fragments.add(meFragment);

        FragmentManager manager = getSupportFragmentManager();
        FragmentPagerAdapter adapter = new FragmentPagerAdapter(manager) {
            @NonNull
            @Override
            public Fragment getItem(int position) {
                return fragments.get(position);
            }

            @Override
            public int getCount() {
                return fragments.size();
            }
        };
        vpContainer.setOffscreenPageLimit(3);
        vpContainer.setAdapter(adapter);
        vpContainer.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        bytTab.setOnTabChangeListener(idx -> {

        });
        bytTab.setupWithPager(vpContainer);

    }


    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    long lastBack = 0;

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            long nowTimestamp = new Date().getTime();
            if (nowTimestamp - lastBack < 3000) {
                finish();
            } else {
                ToastUtil.makeShort("再次点击退出");
                lastBack = nowTimestamp;
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


//    @Override
//    @AfterPermissionGranted(8848)
//    public void withCameraPermission(VoidFunction func) {
//        String[] perms = {Manifest.permission.CAMERA};
//        if (EasyPermissions.hasPermissions(this, perms)) {
//            func.call();
//        } else {
//            EasyPermissions.requestPermissions(this, getString(R.string.request_camera), 8848, perms);
//        }
//    }


    private void initData() {
        EZOpenSDK.setAccessToken(AppData.getYsToken());
        String phoneNumber = AppData.getUserInfo().getMobile();
        Disposable disposable = HttpClient.getUser().getUserDetail(phoneNumber).compose(RxSchedulers.io_main()).compose(ResultTransformer.handleResult())
                .subscribe(data -> {
                    JsonObject info = data.get().getAsJsonObject();
//                    if (info.get("code").getAsInt() == 200) {
//                        String uf = info.get("data").getAsString();
                        UserInfo user = new Gson().fromJson(info, UserInfo.class);
                        UserInfo oldUser = AppData.getUserInfo();
                        oldUser.setHeadimg(user.getHeadimg());
                        oldUser.setUsername(user.getUsername());
                        oldUser.setMobile(user.getMobile());
                        oldUser.setNickname(user.getNickname());
                        oldUser.setMarkPhone(user.getMarkPhone());
                        AppData.setUserInfo(oldUser);
//                    } else if (info.get("code").getAsInt() == 501) {
//                        ToastUtil.makeShort("登录信息过期, 请重新登录");
//                        Intent intent = new Intent(MainApplication.getAppContext(), LoginActivity.class);
//                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//                        MainApplication.getAppContext().startActivity(intent);
//                    }


                }, throwable -> {

                });
        addDisposable(disposable);
        // 取一次消息数量
        MessageHandler.onMessage(true);
    }

}